import { login, logout, getInfo, switchRole } from '@/api/rbac/User'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,constantRoutes } from '@/router'
import router from '@/router'
import store from '@/store'
import { setDict } from '@/utils/dict' // get token from cookie
import { initPageElement } from '@/utils/pageElement'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roleInfos: [],
    currentRole:{}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, roleInfos) => {
    state.roleInfos = roleInfos
  },
  SET_CURRENT_ROLE: (state, currentRole) => {
    state.currentRole = currentRole
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.Authorization)
        setToken(data.Authorization)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { userName, headUrl } = data
        const { roleCodes, roleNames } = data
        const { currentRole } = data
        let roleCodesArray = roleCodes.split(',')
        let roleNamesArray = roleNames.split(',')
        let roleInfos = [];
        for(var i=0;i<roleCodesArray.length;i++){
          let roleInfo = {};
          if(roleCodesArray[i] != currentRole.id){
            roleInfo.roleId = roleCodesArray[i]
            roleInfo.roleName = roleNamesArray[i]
            roleInfos.push(roleInfo)
          }
        }
        commit('SET_CURRENT_ROLE', currentRole)
        commit('SET_ROLE', roleInfos)
        commit('SET_NAME', userName)
        commit('SET_AVATAR', headUrl || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        sessionStorage.removeItem('dictList')
        sessionStorage.removeItem('menuList')
        sessionStorage.removeItem('routeList')
        sessionStorage.removeItem('pageElementList')
        // dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  switchRole({ commit }, roleId){
    return new Promise((resolve, reject) => {
      switchRole({ roleId: roleId}).then(response => {
        const { data } = response
        if(data){ // 切换成功
          router.push('/')
          resetRouter()
          commit('RESET_STATE')
          sessionStorage.removeItem('dictList')
          sessionStorage.removeItem('menuList')
          sessionStorage.removeItem('routeList')
          sessionStorage.removeItem('pageElementList')
          location.reload()
          
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

